# coding=utf-8
__author__ = 'liubin'

from sqlalchemy import Column, Integer, String, ForeignKey, Table
from sqlalchemy.orm import relationship
from project import db

# 关系表 用户和权限的多链接
user_role_assoc_table = Table('user_role_assoc', db.metadata,
                              # 用户ID
                              Column('user_id', Integer, ForeignKey('user_tab.id')),
                              # 权限ID
                              Column('role_id', Integer, ForeignKey('role_tab.id'))
)


class User(db.Model):
    """
    用户表
    """
    __tablename__ = 'user_tab'

    # ID
    id = Column(Integer, primary_key=True)
    # 登录名称
    name = Column(String(50), unique=True, index=True, nullable=False)
    # 表示名称
    real_name = Column(String(50), nullable=False)
    # 密码
    pwd = Column(String(128), nullable=False)
    # 所属权限
    roles = relationship("Role", secondary=user_role_assoc_table, backref="roles")


    def __init__(self, name=None, pwd=None, real_name=None):
        """
        构造函数
        :param name:
        :param pwd:
        :param role_id:
        :return:
        """
        self.name = name
        self.pwd = pwd
        self.real_name = real_name

    def is_authenticated(self):
        """
        是否验证成功
        在这里，登录成功后都返回True
        :return:
        """
        return True

    def is_active(self):
        """
        是否可用
        在这里，登录成功后都返回True
        :return:
        """
        return True

    def is_anonymous(self):
        """
        sh
        :return:
        """
        return False

    def get_id(self):
        return unicode(self.id)

    def __unicode__(self):
        return self.name


class Role(db.Model):
    __tablename__ = 'role_tab'
    id = Column(Integer, primary_key=True)
    code = Column(String(20), unique=True, index=True, nullable=False)
    name = Column(String(50), nullable=False)

    def __init__(self, code=None, name=None):
        self.code = code
        self.name = name

    def __unicode__(self):
        return self.name